package Demo11;


import java.sql.*;

public class SqlHelper {
    private static Connection conn;
    public static Connection getConn() throws ClassNotFoundException, SQLException{
        //1.加载驱动程序
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//        Class.forName("com.microsogt.jdbc.sqlserver.SQLServerDriver");
        //Class.forName("com.mysql.cj.jdbc.Driver");  mysql
        //2.创建一个连接
        String url="jdbc:sqlserver://localhost:1433;databaseName=soft1901";
        conn=DriverManager.getConnection(url,"sa","x");
        //conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_demo","root","password");
        return conn;
    }
    public static void closeConn(){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        try {
            Connection c=getConn();
//            System.out.print("数据库连接成功！");
            //添加数据
            //--------------查询
            //1，创建statement的一个对象
            Statement state=c.createStatement();
            //2，编写sql语句
//            String sql="insert into student values('001','小艾','男','四川','团员','学生')";
            String sql="select  * from student";
            //执行sql
//            int n= state.executeUpdate(sql);
            ResultSet rs=state.executeQuery(sql);///查询 ---
            //---显示数据
            System.out.println("学号\t姓名\t性别\t年龄");
            //----循环显示
            while (rs.next()){
                String id=rs.getString("stuID");
                String name=rs.getString("stuName");
                String sex=rs.getString("stuSex");
                int age=rs.getInt("stuAge");
                System.out.println(id+"\t"+name+"\t"+sex+"\t"+age+"\n");
            }

//            System.out.println(n+"条记录被插入");
            //4，关闭连接
            closeConn();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

    }
}
//import java.sql.Connection;
//import java.sql.SQLException;
//
//public class SqlHelper {
////    JDBC Java DataBase Commection   增删改查   ---打开--》操作--》关闭
//    private  static Connection conn;
//
//    public static Connection getConn() throws ClassNotFoundException, SQLException {
//        //加载驱动程序
//        Class.forName("com.microsoft.sqlserver.jdbc.");
//
//        return conn;
//    }
//
//
//}
